package cn.kiliter.dao;

import cn.kiliter.model.Product;
import cn.kiliter.utils.C3P0Utils;
import cn.kiliter.utils.ManagerThreadLocal;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ProductDao {
    private QueryRunner qr=new QueryRunner(C3P0Utils.getDataSource());

    public  long findTotalCount(String category)throws SQLException {
        long totalCount=0;
        String sql="select count(*) from products where 1=1 ";
        if(!"".equals(category)&&category!=null){
            sql+=" and category = ? ";
            totalCount = (long)qr.query(sql, new ScalarHandler(1), category);
        }
        else {
            totalCount = (long)qr.query(sql, new ScalarHandler(1));
        }
        return totalCount;
    }


    public List<Product> findList(int currentPage, int pageSize, String category) throws SQLException {
        String sql="select * from products where 1=1 ";
        List<Object>list=new ArrayList<>();
        if(!"".equals(category)&&category!=null){
            sql+=" and category = ? ";
            list.add(category);
        }
        sql+=" limit ?,?";
        int start=(currentPage-1)*pageSize;
        list.add(start);
        list.add(pageSize);
        return qr.query(sql,new BeanListHandler<Product>(Product.class),list.toArray());
    }

    public Product findProDuctById(int id) throws SQLException {
        String sql="select * from products where id=? ";
        return qr.query(sql,new BeanHandler<Product>(Product.class),id);

    }
    public void saveorder(int id,int buynum) throws SQLException {
        String sql="update products set pnum=pnum-? where id =?";
        qr.update(ManagerThreadLocal.getConnection(),sql,buynum,id);
    }
}
